export let xLoginConfig = {
  showError: true,
  saveUserInfoAfterLogin: true,
  getUserInfoAfterLogin: false,
  redirectAfterLogin: 'home',
  descGetUserInfo: '获取您的头像与昵称用于显示',
  getUserInfoOnShow: false,
}

/**
 * 密码登录
 */
 export let xLoginNormal = {
  _url: '',
  _field: {
    username: 'username',
    password: 'password',
    code: 'code',
  },
  data() {
    return {
      xLoginParamNormal: {
        [xLoginNormal._field.username]: '',
        [xLoginNormal._field.password]: '',
        [xLoginNormal._field.code]: '',
      },
      xLoginParamNormalRule: {
        [xLoginNormal._field.username]: [{'required': true, message: '请输入用户名'}],
        [xLoginNormal._field.password]: [{'required': true, message: '请输入密码'}],
        [xLoginNormal._field.code]: [{'required': true, message: '请输入验证码'}],
      },
      xLoginNormalPasswordType: 'password',
      needGeneratePhone: false, // 是否需要随机生成手机号，默认不需要
    }
  },
  onLoad(query) {
    this.redirectAfterLogin = query.redirectAfterLogin
  },
  methods: {
    // ==================
    // 登录
    // ==================
    xLoginNormalRequest(req) {
      return req
    },
    xLoginNormalResponse(res, req) {
      return res
    },
    xLoginNormalGetToken(res, req) {
      return res.token
    },
    xLoginNormalGetUserInfo(res, req) {
      return res
    },
    xLoginNormalSuccess(token, userInfo, res, req) {
      console.log('xlogin xLoginNormal:', res)
      this.xLoginIsLogin = true
      uni.$x.auth.logined(token)

      if(xLoginConfig.saveUserInfoAfterLogin) uni.$x.auth.setUserInfo(userInfo)
      if(xLoginConfig.getUserInfoAfterLogin) this.xLoginGetMemberInfo()

      let redirectAfterLogin = this.redirectAfterLogin||xLoginConfig.redirectAfterLogin
      if(redirectAfterLogin==='home') {
        // #ifdef XT_PC
        let {redirect=uni.$x.navigator.route.home, ...query} = this.$route.query
        uni.$x.navigator.replace(redirect, query)
        // #endif
        // #ifndef XT_PC
        uni.$x.navigator.relaunch()
        // #endif
      }else if(redirectAfterLogin==='back') {
        uni.$x.navigator.back()
      }

      return res
    },
    xLoginNormal() {
      console.log('xlogin xLoginNormal')
      let requestData = this.xLoginNormalRequest({
        url: xLoginNormal._url || uni.$x.request.url.xLoginNormal,
        data: { ...this.xLoginParamNormal },
        method: 'POST',
        showError: xLoginConfig.showError,
        ...xLoginNormal.requestOptions
      })
      if(requestData===false) return Promise.reject()
      return uni.$x.request.request(requestData).then(res => {
        console.log('xlogin xLoginNormal:',res)
        res = this.xLoginNormalResponse(res, requestData)
        if(res===false) return Promise.reject();
        return (this.xLoginNormalSuccessBefore?this.xLoginNormalSuccessBefore(res):Promise.resolve()).then(()=>{
          return this.xLoginNormalSuccess(this.xLoginNormalGetToken(res, requestData), this.xLoginNormalGetUserInfo(res, requestData), res, requestData)
        })
      }).catch(err=>{
        console.log('xlogin xLoginNormal err:', err)
        throw err
      })
    },
  }
}

/**
 * 验证码登录
 */
 export let xLoginPhone = {
  data() {
    return {
      xLoginCodeTip: '',
      xLoginCodeDisabled: '',
      xLoginParamPhone: {
        mobile: '13842042878',
        code: '',
        password: ''
      },
      xLoginParamPhoneRule: {
        mobile: {rules:[
          {'required': true,errorMessage: '请输入手机号'},
          {'pattern': '^[1][3-9][0-9]{9}$', errorMessage: '请输入正确手机号'}
        ]},
        code: {rules:[{'required': true, errorMessage: '请输入验证码'}]},
        password: {rules:[{'required': true, errorMessage: '请输入如密码'}]},
      },
    }
  },
  methods: {
    // ==================
    // 验证码登录
    // ==================
    xLoginPhoneByVerifyCodeRequest(req) {
      return req
    },
    xLoginPhoneByVerifyCodeBind(req) {
      if(this.xLoginPartyForceBind) {
        req.data = req.data || {}
        req.data.bind_data = this.xLoginPartyBindData.data||undefined
      }
      return req
    },
    xLoginPhoneByVerifyCodeResponse(res) {
      return res
    },
    xLoginPhoneByVerifyCodeSuccess(res) {
      console.log('xlogin xLoginPhoneByVerifyCodeSuccess:', res)
      this.xLoginIsLogin = true
      uni.$x.auth.logined(res.token)
      if(this.xLoginIsLogin&&this.xLoginAutoGetMemberInfoOnLogined) this.xLoginGetMemberInfo()
      return res
    },
    xLoginPhoneByVerifyCode() {
      console.log('xlogin xLoginPhoneByVerifyCode')
      let requestData = this.xLoginPhoneByVerifyCodeRequest({
        url: uni.$x.request.url.xLoginPhoneByVerifyCode,
        data: this.xLoginParamPhone,
        method: 'POST'
      })
      if(requestData===false) return Promise.reject()
      requestData = this.xLoginPhoneByVerifyCodeBind(requestData)
      return uni.$x.request.request(requestData).then(res => {
        console.log('xlogin xLoginPhoneByVerifyCode:',res)
        res = this.xLoginPhoneByVerifyCodeResponse(res)
        if(res===false) return Promise.reject()
        return this.xLoginPhoneByVerifyCodeSuccess(res)
      }).catch(err=>{
        console.log('xlogin xLoginPhoneByVerifyCode err:', err)
        throw {
          ...err||{},
          code: 'request',
        }
      })
    },

    // ==================
    // 获取验证码
    // ==================
    xLogingPhoneGetVerifyCodeRequest(req) {
      return req
    },
    xLogingPhoneGetVerifyCodeResponse(res) {
      return res
    },
    xLogingPhoneGetVerifyCodeSuccess(res) {
      uni.$x.notify.showToast('验证码已发送');
      return res
    },
    xLogingPhoneGetVerifyCode() {
      console.log('xlogin xLogingPhoneGetVerifyCode')
      let requestData = this.xLogingPhoneGetVerifyCodeRequest({
        url: uni.$x.request.url.xLoginSendVerifyCode,
        data: this.xLoginParamPhone,
        method: 'POST'
      })
      if(requestData===false) return Promise.reject()
      return uni.$x.request.request(requestData).then(res => {
        console.log('xlogin xLogingGetVerifyCode:',res)
        res = this.xLogingPhoneGetVerifyCodeResponse(res)
        if(res===false) return Promise.reject()
        return this.xLogingPhoneGetVerifyCodeSuccess(res)
      }).catch(err=>{
        console.log('xlogin xLogingGetVerifyCode err:', err)
        throw {
          ...err||{},
          code: 'getVerifyCode',
        }
      })
    },
  }
}

/**
 * 容器平台登录
 */
export let xLoginPlatform = {
  _url: '',
  _field: {
    code: 'code',
    phoneCode: 'phoneCode',
    encryptedData: 'encryptedData',
    iv: 'iv',
    nickname: 'nickname',
    avatar: 'avatar',
  },
  _asyncCode: false,
  _secondUIField: 'UserInfo',
  data() {
    return {
      xLoginParamPlatLoging: false,
      xLoginParamPlatform:{
        [xLoginPlatform._field.code]: '',
        [xLoginPlatform._field.phoneCode]: '',
        [xLoginPlatform._field.encryptedData]: '',
        [xLoginPlatform._field.iv]: '',
        [xLoginPlatform._field.nickname]: '',
        [xLoginPlatform._field.avatar]: '',
      },
      xLoginPlatformLoginFirstRes: undefined,
      xLoginPlatformLoginSecondNeedUserInfo: false,
      xLoginPlatformLoginSecondNeedPhone: false,
    }
  },
  onLoad(query) {
    this.redirectAfterLogin = query.redirectAfterLogin
  },
  onShow() {
    if(xLoginPlatform._asyncCode) this.xLoginPlatformGetCode()
  },
  methods: {
    // ==================
    // 错误处理
    // ==================
    xLoginPlatformGetUserInfoFail(msg, data) {
      this.xLoginParamPlatLoging = false
      if(xLoginConfig.showError) uni.$x.notify.showToast(msg)
    },
    xLoginPlatformGetPhoneFail(msg, data) {
      this.xLoginParamPlatLoging = false
      if(xLoginConfig.showError) uni.$x.notify.showToast(msg)
    },
    // ==================
    // 容器平台数据获取
    // ==================
    /**
     * 平台 code
     */
    xLoginPlatformGetCode() {
      return uni.login({
        // #ifdef MP-WEIXIN
        provider: 'weixin',
        // #endif
      }).then(([err, res])=>{
        if(err) {
          if(xLoginConfig.showError) uni.$x.notify.handleException(err)
          throw err
        }
        this.xLoginParamPlatform[xLoginPlatform._field.code] = res.code
        return res.code
      })
    },
    /**
     * 手机号获取回仅保存
     */
     xLoginPlatformGetPhoneCB(data) {
      console.log('xlogin xLoginPlatformGetPhoneNumber:', data)
      if(data.detail.errMsg!='getPhoneNumber:ok') {
        this.xLoginPlatformGetPhoneFail(data.detail.errMsg, data)
      }else{
        this.xLoginParamPlatform[xLoginPlatform._field.code] = ''
        // #ifdef MP-WEIXIN
        this.xLoginParamPlatform[xLoginPlatform._field.phoneCode] = data.detail.code
        // #endif
        // #ifndef MP-WEIXIN
        this.xLoginParamPlatform[xLoginPlatform._field.encryptedData] = data.detail.encryptedData
        this.xLoginParamPlatform[xLoginPlatform._field.iv] = data.detail.iv
        // #endif
      }
    },
    /**
     * 用户信息获取回仅保存
     */
    xLoginPlatformGetUserInfo(avatar, nickname) {
      console.log('xlogin xLoginPlatformGetUserInfo')
      
      if(this.avatar||this.nickname) {
        this.xLoginParamPlatform[xLoginPlatform._field.nickname] = nickname
        this.xLoginParamPlatform[xLoginPlatform._field.avatar] = avatar
        this.xLoginParamPlatform.nickName = nickname
        this.xLoginParamPlatform.avatarUrl = avatar
        return Promise.resolve({})
      }

      // #ifdef MP-WEIXIN
      return uni.getUserProfile({
        desc: xLoginConfig.descGetUserInfo,
      }).then(([err, res])=>{
        console.log('xlogin xLoginPlatformGetUserInfo:', err, res)
        if(err) {
          this.xLoginPlatformGetUserInfoFail(err.errMsg, err)
          throw err
        }
        this.xLoginParamPlatform[xLoginPlatform._field.nickname] = nickname||res.nickname
        this.xLoginParamPlatform[xLoginPlatform._field.avatar] = avatar||res.avatar
        this.xLoginParamPlatform[xLoginPlatform._field.nickName] = nickname||res.nickname
        this.xLoginParamPlatform[xLoginPlatform._field.avatarUrl] = avatar||res.avatar
        this.xLoginParamPlatform[xLoginPlatform._field.encryptedData] = res.encryptedData
        this.xLoginParamPlatform[xLoginPlatform._field.iv] = res.iv
        return res
      });
      // #endif
      // #ifndef MP-WEIXIN
      return uni.getUserInfo().then(([err, res])=>{
        console.log('xlogin xLoginPlatformGetUserInfo:', err, res)
        if(err) {
          if(xLoginConfig.showError) uni.$x.notify.showToast(err.errMsg)
          throw err
        }
        this.xLoginParamPlatform[xLoginPlatform._field.nickname] = res.userInfo&&res.userInfo.nickName
        this.xLoginParamPlatform[xLoginPlatform._field.avatar] = res.userInfo&&res.userInfo.avatarUrl
        // this.xLoginParamPlatform[xLoginPlatform._field.encryptedData] = res.encryptedData
        // this.xLoginParamPlatform[xLoginPlatform._field.iv] = res.iv
        return res
      })
      // #endif
    },

    // ==================
    // 容器登录操作
    // ==================
    /**
     * code 登录
     * <button open-type="getPhoneNumber" @getphonenumber="xLoginPlatformGetPhoneNumber" />
     */
    xLoginPlatformLogin(needGeneratePhone=false) {
      this.needGeneratePhone = needGeneratePhone
      console.log('needGeneratePhone:',this.needGeneratePhone,needGeneratePhone)
      this.xLoginParamPlatLoging = true
      return this.xLoginPlatformGetCode().then(res=>{
        return this.xLoginPlatformLoginWork()
      }).catch(()=>{
        this.xLoginParamPlatLoging = false
      })
    },
    xLoginPlatformUserInfoLogin() {
      return this.xLoginPlatformGetUserInfo().then(res=>{
        return this.xLoginPlatformGetCode().then(res=>{
          return this.xLoginPlatformLoginWork()
        })
      })
    },
    xLoginPlatformSecondUserInfoLogin() {
      this.xLoginPlatformLoginSecondNeedUserInfo = false
      return this.xLoginPlatformGetUserInfo().then(res=>{
        return this.xLoginPlatformLoginWork(true)
      })
    },
    xLoginPlatformSecondPhoneLogin(data) {
      this.xLoginPlatformGetPhoneCB(data)
      return this.xLoginPlatformLoginWork(true)
    },
    xLoginPlatformSecondUserInfoBeforePhoneLogin(avatar, nickname) {
      this.xLoginPlatformLoginSecondNeedUserInfo = false
      return this.xLoginPlatformGetUserInfo(avatar, nickname).then(res=>{
        this.xLoginPlatformLoginSecondNeedPhone = true
      }).catch(()=>{
        this.xLoginParamPlatLoging = false
      })
    },
    xLoginPlatformSecondPhoneAfterUserInfoLogin(data) {
      this.xLoginPlatformLoginSecondNeedPhone = false
      this.xLoginPlatformGetPhoneCB(data)
      return this.xLoginPlatformLoginWork(true)
    },
    xLoginPlatformSecondPhoneBeforeUserInfoLogin() {
      this.xLoginPlatformLoginSecondNeedPhone = false
      return this.xLoginPlatformGetUserInfo().then(res=>{
        this.xLoginPlatformLoginSecondNeedUserInfo = true
      })
    },
    xLoginPlatformSecondeUserInfoAfterPhoneLogin() {
      this.xLoginPlatformLoginSecondNeedUserInfo = false
      return this.xLoginPlatformGetUserInfo().then(res=>{
        return this.xLoginPlatformLoginWork(true)
      })
    },
    

    // ==================
    // 平台登录接口
    // ==================
    xLoginPlatformLoginRequest(req) {
      return req
    },
    xLoginPlatformLoginResponse(res) {
      return res
    },
    xLoginPlatformLoginGetToken(res) {
      return res.token
    },
    xLoginPlatformLoginGetUserInfo(res) {
      return res
    },
    xLoginPlatformLoginSuccess(token, userInfo, res) {
      console.log('xlogin xLoginPlatformLoginSuccess:', res)
      this.xLoginIsLogin = true
      uni.$x.auth.logined(token)

      if(xLoginConfig.saveUserInfoAfterLogin) uni.$x.auth.setUserInfo(userInfo)
      if(xLoginConfig.getUserInfoAfterLogin) this.xLoginGetMemberInfo()

      let redirectAfterLogin = this.redirectAfterLogin||xLoginConfig.redirectAfterLogin
      if(redirectAfterLogin==='home') {
        setTimeout(()=>uni.$x.navigator.relaunch(), 100)
      }else if(redirectAfterLogin==='back') {
        uni.$x.navigator.back()
      }

      return res
    },
    xLoginPlatformLoginSecondInfoCheck(res) {
      return this['xLoginPlatformLoginSecondNeed' + xLoginPlatform._secondUIField] = !res.token
    },
    xLoginPlatformLoginWork(second) {
      console.log('xlogin xLoginPlatformLogin: ', second)
      let requestData = this.xLoginPlatformLoginRequest({
        url: xLoginPlatform._url || uni.$x.request.url.xLoginPlatformLogin,
        data: {
          ...(second?this.xLoginPlatformLoginFirstRes:undefined),
          ...this.xLoginParamPlatform,
          needGeneratePhone: this.needGeneratePhone
        },
        method: 'POST'
      })
      return uni.$x.request.request(requestData).then(res => {
        console.log('xlogin xLoginPlatformLogin:', res)
        res = this.xLoginPlatformLoginResponse(res)
        let need = second?false:this.xLoginPlatformLoginSecondInfoCheck(res)

        if(need) {
          this.xLoginPlatformLoginFirstRes = res
          return res
        }else{
          try {
            res = this.xLoginPlatformLoginSuccess(this.xLoginPlatformLoginGetToken(res), this.xLoginPlatformLoginGetUserInfo(res), res)
          } catch(e){
            console.log(1111111, e)
          }
          this.xLoginParamPlatLoging = false
          if(this.xLoginPlatformLoginSuccessCb) this.xLoginPlatformLoginSuccessCb(res)
          return res
        }
      }).catch(err => {
        console.log('xlogin xLoginPlatformLogin err:', err)
        this.xLoginParamPlatLoging = false
        if(this.xLoginPlatformLoginFailCb) this.xLoginPlatformLoginFailCb(err)
        throw err
      }).finally(()=>{
        if(xLoginPlatform._asyncCode) this.xLoginPlatformGetCode()
      })
    },
  }
}

/**
 * 第三方登录与绑定
 */
export let xLoginParty = {
  _url: '',
  _field: {
    code: 'code',
    gender: 'gender',
    headImg: 'headImg',
    phone: 'phone',
    nickname: 'nickname',
    unionId: 'unionId',
  },
  data() {
    return {
      xLoginPartyBindData: {},
      xLoginPartyForceBind: false,
    }
  },
  methods: {
    // ==================
    // 苹果登录
    // ==================
    xLoginPartyByAppleRequest(requestData) {
      return requestData
    },
    xLoginPartyByAppleResponse(responseData) {
      return responseData
    },
    xLoginPartyByAppleCheckBind(responseData) {
      return responseData.error_code===1403
    },
    xLoginPartyByAppleSuccess(responseData) {
      console.log('xlogin xLoginPartyByAppleSuccess: ', responseData)
      this.xLoginIsLogin = true
      uni.$x.auth.logined(responseData.token)
      if(this.xLoginIsLogin&&this.xLoginAutoGetMemberInfoOnLogined) this.xLoginGetMemberInfo()
      return responseData
    },
    xLoginPartyByApple() {
      console.log('xLogin xLoginPartyByApple')
      let phase = 'login'
      this.xLoginPartyForceBind = false
      this.xLoginGetUserInfoOnShowDisabled = true
      return uni.login({ provider: 'apple' }).then(()=>{
        phase = 'getUserInfo'
        return uni.getUserInfo({ provider: 'apple' })
      }).then(res=>{
        phase = 'request'
        let requestData = {
          url: uni.$x.request.url.xLoginPartyByApple,
          showError: false,
          method: "POST",
          data: {
            "token": res.userInfo.identityToken
          }
        }
        requestData = this.xLoginPartyByAppleRequest(requestData)
        if(requestData===false) throw ''
        return uni.$x.request.request(requestData)
      }).then(res => {
        phase = 'response'
        console.log('xLogin xLoginPartyByApple res: ', res)
        this.xLoginGetUserInfoOnShowDisabled = false
        res = this.xLoginPartyByAppleResponse(res)
        if(res===false) throw ''
        if(this.xLoginPartyByAppleCheckBind(res)) {
          console.log('xLogin xLoginPartyByApple need bind')
          this.$set(this, 'xLoginPartyBindData', res)
          this.xLoginPartyForceBind = true
          return res
        }else{
          this.xLoginPartyForceBind = false
          return this.xLoginPartyByAppleSuccess(res)
        }
      }).catch(err=>{
        console.log(`xlogin xLoginPartyByApple ${phase} err:`, err)
        throw {
          code: phase,
          message: phase==='authorize'?'授权失败':err.message,
          data: err,
        }
      }).finally(()=>{
        this.xLoginGetUserInfoOnShowDisabled = false
      })
    },
    // ==================
    // 苹果绑定
    // ==================
    xLoginPartyBindByAppleRequest(requestData) {
      return requestData
    },
    xLoginPartyBindByAppleBind(req) {
      req.data = req.data || {}
      req.data.is_bind = true
      return req
    },
    xLoginPartyBindByAppleResponse(responseData) {
      return responseData
    },
    xLoginPartyBindByAppleSuccess(responseData) {
      uni.$x.notify.showToast('授权成功')
      return responseData
    },
    xLoginPartyBindByApple() {
      console.log('xLogin xLoginPartyBindByApple')
      let phase = 'login'
      this.xLoginGetUserInfoOnShowDisabled = true
      uni.login({ provider: 'apple' }).then(()=>{
        phase = 'getUserInfo'
        return uni.getUserInfo({ provider: 'apple' })
      }).then(res=>{
        phase = 'request'
        let requestData = this.xLoginPartyBindByAppleRequest({
          url: uni.$x.request.url.xLoginPartyBindByApple,
          showError: false,
          method: "POST",
          data: { "token": res.userInfo.identityToken }
        })
        if(requestData===false) return Promise.reject()
        requestData = this.xLoginPartyBindByAppleBind(requestData)
        return uni.$x.request.request(requestData)
      }).then(res => {
        phase = 'response'
        console.log('xLogin xLoginPartyBindByApple res: ', res)
        this.xLoginGetUserInfoOnShowDisabled = false
        res = this.xLoginPartyBindByAppleResponse(res)
        if(res===false) return Promise.reject()
        return this.xLoginPartyBindByAppleSuccess(res)
      }).catch(err=>{
        console.log(`xlogin xLoginPartyBindByApple ${phase} err:`, err)
        throw {
          code: phase,
          message: phase==='authorize'?'授权失败':err.message,
          data: err,
        }
      }).finally(()=>{
        this.xLoginGetUserInfoOnShowDisabled = false
      })
    },
    // ==================
    // 苹果解绑
    // ==================
    xLoginPartyUnbindByAppleRequest(req) {
      return req
    },
    xLoginPartyUnbindByAppleResponse(res) {
      return res
    },
    xLoginPartyUnbindByAppleSuccess(res) {
      return res
    },
    xLoginPartyUnbindByApple() {
      console.log('xLogin xLoginPartyUnbindByApple')
      let requestData = this.xLoginPartyUnbindByAppleRequest({
        url: uni.$x.request.url.xLoginPartyUnbindByApple,
        showError: false,
        params: {provider: 'apple'},
      })
      if(requestData===false) return Promise.reject()
      return uni.$x.request.request(requestData).then(res => {
        console.log('xLogin xLoginPartyUnbindByApple res: ', res)
        res = this.xLoginPartyUnbindByAppleResponse(res)
        if(res===false) return Promise.reject()
        return this.xLoginPartyUnbindByAppleSuccess(res)
      }).catch(err=>{
        console.log(`xlogin xLoginPartyUnbindByApple err:`, err)
        throw {
          ...err,
          code: 'request',
        }
      })
    },
    xLoginPartyUnbindByAppleConfirm() {
      return uni.$x.notify.showModal({content: '是否解绑苹果账号？'}).then(()=>{
        return this.xLoginPartyUnbindByApple()
      })
    },


    // ==================
    // 微信登录
    // ==================
    xLoginPartyByWeChatRequest(req) {
      return req
    },
    xLoginPartyByWeChatResponse(res) {
      return res
    },
    xLoginPartyByWeChatCheckBind(responseData) {
      return responseData.error_code===1403
    },
    xLoginPartyByWeChatSuccess(token, userInfo, res, req) {
      console.log('xlogin xLoginPartyByWeChatSuccess token:', 'userInfo:', userInfo, 'res:', res,)
      this.xLoginIsLogin = true
      uni.$x.auth.logined(res.token)
      // if(this.xLoginIsLogin&&this.xLoginAutoGetMemberInfoOnLogined) this.xLoginGetMemberInfo()
      // return res

      if(xLoginConfig.saveUserInfoAfterLogin) uni.$x.auth.setUserInfo(userInfo)
      if(xLoginConfig.getUserInfoAfterLogin) this.xLoginGetMemberInfo()

      let redirectAfterLogin = this.redirectAfterLogin||xLoginConfig.redirectAfterLogin
      if(redirectAfterLogin==='home') {
        setTimeout(()=>uni.$x.navigator.relaunch(), 100)
      }else if(redirectAfterLogin==='back') {
        uni.$x.navigator.back()
      }

      return res
    },
    xLoginPartyByWeChat() {
      let phase = 'authorize'
      let requestData
      console.log('xLoginPartyByWeChat 111')
      this.xLoginPartyForceBind = false
      this.xLoginGetUserInfoOnShowDisabled = true
      return new Promise((resolve, reject)=>{
        plus.oauth.getServices(services=>{
          console.log('plus.oauth.getServices',services)
          let aweixin = services.find(v=>v.id==='weixin')
          if(!aweixin) reject('no wechat')
          aweixin.authorize(res=>{
            resolve(res)
          },err=>{
            reject(err)
          })
        })
      }).then(res=>{
        console.log('xLoginPartyByWeChat 222',res)
        phase = 'request'
        requestData = this.xLoginPartyByWeChatRequest({
          // url: uni.$x.request.url.xLoginPartyByWeChat,
          url: xLoginParty._url,
          // || uni.$x.request.url.xLoginPartyByWeChat,
          method: "POST",
          showError: false,
          data: { 
            code: res.code,
          }
        })
        if(requestData===false) throw ''
        return uni.$x.request.request(requestData)
      }).then(res=>{
        console.log('xLoginPartyByWeChat 333', res)
        res = this.xLoginPartyByWeChatResponse(res)
        this.xLoginGetUserInfoOnShowDisabled = false
        if(res===false) throw ''
        if(this.xLoginPartyByWeChatCheckBind(res)) {
          console.log('xLogin xLoginPartyByWeChat 444 need bind')
          this.$set(this, 'xLoginPartyBindData', res)
          this.xLoginPartyForceBind = true
          return res
        }else{
          this.xLoginPartyForceBind = false
          // return this.xLoginPartyByWeChatSuccess(res)
          return this.xLoginPartyByWeChatSuccess(this.xLoginNormalGetToken(res, requestData), this.xLoginNormalGetUserInfo(res, requestData), res, requestData)
        }
        // let requestData = this.xLoginNormalRequest({
        //   url: xLoginNormal._url || uni.$x.request.url.xLoginNormal,
        //   data: { ...this.xLoginParamNormal },
        //   method: 'POST',
        //   showError: xLoginConfig.showError,
        //   ...xLoginNormal.requestOptions
        // })
        // if(requestData===false) return Promise.reject()
        // return uni.$x.request.request(requestData).then(res => {
        //   console.log('xlogin xLoginNormal:',res)
        //   res = this.xLoginNormalResponse(res, requestData)
        //   if(res===false) return Promise.reject()
        //   return this.xLoginNormalSuccess(this.xLoginNormalGetToken(res, requestData), this.xLoginNormalGetUserInfo(res, requestData), res, requestData)
        // }).catch(err=>{
        //   console.log('xlogin xLoginNormal err:', err)
        //   throw err
        // })
      }).catch(err=>{
        console.log(`xLogin xLoginPartyByWeChat ${phase} err: `, err)
        throw {
          code: phase,
          message: phase==='authorize'?'授权失败':err.message,
          data: err,
        }

      }).finally(()=>{
        this.xLoginGetUserInfoOnShowDisabled = false
      })
    },

    // ==================
    // 微信绑定
    // ==================
    xLoginPartyBindByWeChatRequest(req) {
      return req
    },
    xLoginPartyBindByWeChatBind(req) {
      req.data = req.data || {}
      req.data.is_bind = true
      return req
    },
    xLoginPartyBindByWeChatResponse(res) {
      return res
    },
    xLoginPartyBindByWeChatSucess(res) {
      uni.$x.notify.showToast('授权成功')
      return res
    },
    xLoginPartyBindByWeChat() {
      let phase = 'authorize'
      console.log('xLogin xLoginPartyBindByWeChat')
      this.xLoginGetUserInfoOnShowDisabled = true
      return new Promise((resolve, reject)=>{
        plus.oauth.getServices(services=>{
          let aweixin = services.find(v=>v.id==='weixin')
          if(!aweixin) reject('no wechat')
          aweixin.authorize(res=>{
            resolve(res)
          },err=>{
            reject(err)
          })
        })
      }).then(res=>{
        phase = 'request'
        let requestData = this.xLoginPartyBindByWeChatRequest({
          url: uni.$x.request.url.xLoginPartyBindByWeChat,
          method: "POST",
          showError: false,
          data: { code: res.code }
        })
        if(requestData===false) return Promise.reject()
        requestData = this.xLoginPartyBindByWeChatBind(requestData)
        return uni.$x.request.request(requestData)
      }).then(res=>{
        console.log('xLogin xLoginPartyBindByWeChat: ', res)
        res = this.xLoginPartyBindByWeChatResponse(res)
        this.xLoginGetUserInfoOnShowDisabled = false
        if(res===false) return Promise.reject()
        return this.xLoginPartyBindByWeChatSucess(res)
      }).catch(err=>{
        console.log(`xLogin xLoginPartyBindByWeChat ${phase} err: `, err)
        throw {
          code: phase,
          message: phase==='authorize'?'授权失败':err.message,
          data: err,
        }
      }).finally(()=>{
        this.xLoginGetUserInfoOnShowDisabled = false
      })
    },

    // ==================
    // 微信解绑
    // ==================
    xLoginPartyUnbindByWeChatRequest(req) {
      return req
    },
    xLoginPartyUnbindByWeChatResponse(res) {
      return res
    },
    xLoginPartyUnbindByWeChatSuccess(res) {
      return res
    },
    xLoginPartyUnbindByWeChat() {
      console.log('xLogin xLoginPartyUnbindByWeChat')
      let requestData = this.xLoginPartyUnbindByWeChatRequest({
        url: uni.$x.request.url.xLoginPartyUnbindByWeChat,
        showError: false,
        params: {provider: 'wechat'},
      })
      if(requestData===false) return Promise.reject()
      return uni.$x.request.request(requestData).then(res => {
        console.log('xLogin xLoginPartyUnbindByWeChat res: ', res)
        res = this.xLoginPartyUnbindByWeChatResponse(res)
        if(res===false) return Promise.reject()
        return this.xLoginPartyUnbindByWeChatSuccess(res)
      }).catch(err=>{
        console.log(`xlogin xLoginPartyUnbindByWeChat err:`, err)
        throw {
          ...err||{},
          code: 'request',
        }
      })
    },
    xLoginPartyUnbindByWeChatConfirm() {
      return uni.$x.notify.showModal({content: '是否解绑微信账号？'}).then(()=>{
        return this.xLoginPartyUnbindByWeChat()
      })
    },
  }
}

/**
 * 登录状态与用户信息
 */
export let xLoginStatus = {
  _url: '',

  data() {
    return {
      xLoginIsLogin: false, // 登录状态
      xLoginMemberInfo: {}, // 用户信息
      xLoginGetUserInfoOnShowDisabled: false, // 有时第三方登录期间需要临时禁用
    }
  },
  // ==================
  // 更新
  // ==================
  onShow() {
    this.doOnShow()
  },
  mounted() {
    uni.$on(uni.$x.auth.keys.eventLogined, this.xLoginStatusUpdae)
    uni.$on(uni.$x.auth.keys.eventLogouted, this.xLoginStatusUpdae)
    this.getData()
  },
  beforeDestroy() {
    uni.$off(uni.$x.auth.keys.eventLogined, this.xLoginStatusUpdae)
    uni.$off(uni.$x.auth.keys.eventLogouted, this.xLoginStatusUpdae)
  },
  methods: {
    doOnShow() {
      this.xLoginIsLogin = uni.$x.auth.isLogin()
      if(this.xLoginIsLogin&&xLoginConfig.getUserInfoOnShow&&(!this.xLoginGetUserInfoOnShowDisabled)) this.xLoginGetMemberInfo()
    },
    xLoginStatusUpdae() {
      this.xLoginIsLogin = uni.$x.auth.isLogin()
    },
    getData() {
      this.xLoginStatusUpdae()
    },
    // ==================
    // 注销
    // ==================
    xLoginLogoutConfirm() {
      uni.$x.notify.showModal({content: '是否退出登录？'}).then(()=>{
        this.xLoginLogout()
      })
    },
    xLoginLogoutNetwork() {
      return Promise.resolve()
    },
    xLoginLogout() {
      this.xLoginLogoutNetwork().then(()=>{
        this.xLoginIsLogin = false
        uni.$x.auth.logouted()
        uni.$x.navigator.relaunch()
      })
    },
    // ==================
    // 用户信息
    // ==================
    xLoginGetMemberInfoRequest(requestData) {
      return requestData
    },
    xLoginGetMemberInfoResponse(responseData) {
      return responseData
    },
    xLoginGetMemberInfoSuccess(responseData) {
      this.$set(this, 'xLoginMemberInfo', responseData)
      return responseData
    },
    xLoginGetMemberInfo() {
      console.log('xLogin xLoginGetMemberInfo')
      let requestData = {
        url: xLoginStatus._url || uni.$x.request.url.xLoginGetMemberInfo,
      }
      requestData = this.xLoginGetMemberInfoRequest(requestData)
      console.log('xLogin xLoginGetMemberInfo requestData',requestData)
      if(requestData===false) return Promise.reject()
      return uni.$x.request.request(requestData).then(res=>{
        console.log('xLogin xLoginGetMemberInfo res: ', res)
        res = this.xLoginGetMemberInfoResponse(res)
        if(res===false) return Promise.reject()
        return this.xLoginGetMemberInfoSuccess(res)
      })
    },

    // ==================
    // 容器平台获取信息
    // ==================
    // <button open-type="getPhoneNumber" @getphonenumber="xLoginPlatformGetPhoneNumber" />
    xLoginStatusGetUserProfile({raw=false, desc='用于头像和昵称读取', showError=xLoginConfig.showError}={}) {
      return uni.getUserProfile({
        desc,
      }).then(([err, res])=>{
        if(err) {
          if(showError) uni.$x.notify.showToast(err.errMsg)
          throw err
        }
        return raw?res:res.userInfo
      });
    }
  }
}
